package top.leyi.service;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import top.leyi.IService.IFileStorgeService;
import top.leyi.utils.FormatDate;
import top.leyi.utils.RandomString;

import javax.imageio.ImageReader;
import java.io.*;

@Service
public class FileStorgeServiceImpl implements IFileStorgeService {

    @Override
    public String storgeImage(InputStream inputStream, String suffix) throws  IOException{


        /*
         * 组成文件名
         */
        String filename = FormatDate.getYMDFormat1Date() ;
        File file1 = new File(path + filename);
        if(!file1.exists()){
            file1.mkdirs();
        }
        filename  = filename +  "/" + RandomString.getRandomString(20)+suffix;
        File file = new File(path + filename );
        execAyscStorge(()->{
            try{

                /*
                 * 上传文件
                 */
                byte[] bytes = new byte[100];
                OutputStream fout = new FileOutputStream(file);
                while (inputStream.read(bytes) != -1){
                    fout.write(bytes);
                }

                fout.close();
                inputStream.close();
                /*
                 * 缩略图
                 */

                Thumbnails.of(file).scale(.5f).outputQuality(.5).toFile(file);
            }catch (IOException e){

            }
        });


        return prefix + filename;
    }
}